import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: sessionStorage.getItem('token') || '',
    userInfo: JSON.parse(sessionStorage.getItem('userInfo')) || {}
  }),
  actions: {
    // 设置用户信息和token
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    setToken(token) {
      this.token = token
      sessionStorage.setItem('token', token)
    },
    // 登录
    login(userData) {
      // 这里模拟登录，实际项目中应该调用API
      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟成功登录
          const token = 'mock-token-' + Date.now()
          const userInfo = {
            id: 1,
            username: userData.username,
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          }
          this.setToken(token)
          this.setUserInfo(userInfo)
          resolve({ success: true })
        }, 500)
      })
    },
    // 登出
    logout() {
      this.token = ''
      this.userInfo = {}
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
    }
  }
}) 